Page({
  data: {
    formData: {
      type: '支出',
      money: '',
      username: '',
      remark: '',
      date: new Date().toISOString().split('T')[0],
    },
    // 总收入
    totalIncome: 0,
    // 总支出
    totalExpenditure: 0,
    records: [],
    currentMonth: new Date().toISOString().split('T')[0].split('-').slice(0, 2).join('-'),
  },

  onLoad() {
    // 页面加载时自动获取账本数据
    this.fetchRecords();
  },

  handleInputChange(e) {
    const { field } = e.currentTarget.dataset;
    let value = e.detail.value;

    if (field === 'money') {
      value = parseFloat(value).toFixed(2);
    }

    this.setData({
      [`formData.${field}`]: value,
    });
  },

  addRecord() {
    const { formData } = this.data;

    if (!formData.money || !formData.date) {
      wx.showToast({
        title: '请填写完整信息（金额和日期为必填项）',
        icon: 'none',
      });
      return;
    }

    wx.request({
      url: 'http://localhost:8848/account/book/add',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      data: {
        username: formData.username || '匿名用户',
        type: formData.type,
        money: parseFloat(formData.money),
        remark: formData.remark,
        date: formData.date,
      },
      success: (res) => {
        if (res.statusCode === 200) {
          wx.showToast({
            title: '记账成功',
            icon: 'success',
          });
          this.setData({
            formData: {
              type: '支出',
              money: '',
              username: '',
              remark: '',
              date: new Date().toISOString().split('T')[0],
            },
          });
          this.fetchRecords();
        } else {
          wx.showToast({
            title: '记账失败，请重试',
            icon: 'none',
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请检查连接',
          icon: 'none',
        });
      },
    });
  },

  fetchRecords() {
    const { currentMonth } = this.data;
    wx.request({
      url: `http://localhost:8848/account/book/list`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      data: {
        date: currentMonth
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          const records = Array.isArray(res.data.accountbookList) ? res.data.accountbookList : [];
          // 新增总收支计算逻辑
          let totalIncome = 0;
          let totalExpenditure = 0;
          records.forEach(item => {
            if (item.type === '收入') {
              totalIncome += parseFloat(item.money);
            } else {
              totalExpenditure += parseFloat(item.money);
            }
          });
          this.setData({
            records: records,
            totalIncome: totalIncome.toFixed(2),
            totalExpenditure: totalExpenditure.toFixed(2)
          });
        } else {
          wx.showToast({
            title: '获取账单记录失败',
            icon: 'none',
          });
        }
      },
      fail: (err) => {
        console.error('接口调用失败:', err);
        wx.showToast({
          title: '网络错误，请检查连接',
          icon: 'none',
        });
      },
    });
  },

  handleMonthChange(e) {
    const selectedMonth = e.detail.value;
    this.setData({
      currentMonth: selectedMonth,
    });
    this.fetchRecords(); // 切换月份后重新获取账单数据
  },

  // 新增跳转方法
  navigateToAreaLife() {
    wx.navigateTo({
      url: '/pages/area-life/area-life',
    });
  },

  // 新增删除账单方法
  deleteRecord(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
        title: '确认',
        content: '确定要删除该记录吗？',
        success: (res) => {
            if (res.confirm) {
                wx.request({
                    url: `http://localhost:8848/account/book/del/${id}`, // 修复URL路径错误
                    method: 'DELETE',
                    header: {
                        'Authorization': 'Bearer ' + wx.getStorageSync('token')
                    },
                    success: (res) => {
                        if (res.statusCode === 200) {
                            wx.showToast({ title: '删除成功', icon: 'success' });
                            this.fetchRecords();
                        } else {
                            wx.showToast({ title: '删除失败', icon: 'none' });
                        }
                    },
                    fail: () => {
                        wx.showToast({ title: '网络错误', icon: 'none' });
                    }
                });
            }
        }
    });
  },
});